/**
 * 后端 API 测试脚本
 * 运行方式: node test-api.js
 */

const http = require('http');

const BASE_URL = 'http://localhost:3000';
const API_PREFIX = '/api/v1';

// 测试配置
const tests = [
  {
    name: '健康检查',
    method: 'GET',
    path: '/health',
    requiresAuth: false,
  },
  {
    name: '登录接口',
    method: 'POST',
    path: '/auth/login',
    requiresAuth: false,
    body: {
      username: 'admin',
      password: 'admin123',
    },
  },
  {
    name: '获取学生列表',
    method: 'GET',
    path: '/students',
    requiresAuth: true,
  },
  {
    name: '获取教师列表',
    method: 'GET',
    path: '/teachers',
    requiresAuth: true,
  },
  {
    name: '获取班级列表',
    method: 'GET',
    path: '/classes',
    requiresAuth: true,
  },
  {
    name: '获取宿舍列表',
    method: 'GET',
    path: '/dormitories',
    requiresAuth: true,
  },
  {
    name: '获取考勤记录',
    method: 'GET',
    path: '/attendances',
    requiresAuth: true,
  },
  {
    name: '获取成绩列表',
    method: 'GET',
    path: '/grades',
    requiresAuth: true,
  },
];

// 执行 HTTP 请求
function makeRequest(method, path, body = null, token = null) {
  return new Promise((resolve, reject) => {
    const url = new URL(BASE_URL + API_PREFIX + path);
    const options = {
      hostname: url.hostname,
      port: url.port,
      path: url.pathname + url.search,
      method: method,
      headers: {
        'Content-Type': 'application/json',
      },
    };

    if (token) {
      options.headers['Authorization'] = `Bearer ${token}`;
    }

    const req = http.request(options, (res) => {
      let data = '';

      res.on('data', (chunk) => {
        data += chunk;
      });

      res.on('end', () => {
        try {
          const jsonData = data ? JSON.parse(data) : null;
          resolve({
            status: res.statusCode,
            headers: res.headers,
            body: jsonData,
          });
        } catch (e) {
          resolve({
            status: res.statusCode,
            headers: res.headers,
            body: data,
          });
        }
      });
    });

    req.on('error', (error) => {
      reject(error);
    });

    if (body) {
      req.write(JSON.stringify(body));
    }

    req.end();
  });
}

// 运行测试
async function runTests() {
  console.log('🚀 开始测试后端 API...\n');
  console.log(`后端地址: ${BASE_URL}\n`);
  console.log('='.repeat(60));

  let token = null;
  let passedTests = 0;
  let failedTests = 0;

  for (const test of tests) {
    console.log(`\n📋 测试: ${test.name}`);
    console.log(`   方法: ${test.method} ${test.path}`);

    try {
      let response;

      if (test.name === '登录接口') {
        response = await makeRequest(test.method, test.path, test.body);
        if (response.status === 200 && response.body && response.body.success) {
          token = response.body.data?.token;
          console.log(`   ✅ 登录成功，获取到 token`);
          console.log(`   Token: ${token ? token.substring(0, 20) + '...' : 'N/A'}`);
        } else {
          console.log(`   ❌ 登录失败`);
          console.log(`   状态码: ${response.status}`);
          console.log(`   响应:`, JSON.stringify(response.body, null, 2));
        }
      } else if (test.requiresAuth && token) {
        response = await makeRequest(test.method, test.path, null, token);
      } else if (test.requiresAuth && !token) {
        console.log(`   ⏭️  跳过（需要登录，但登录失败）`);
        failedTests++;
        continue;
      } else {
        response = await makeRequest(test.method, test.path);
      }

      if (response.status === 200 || response.status === 201) {
        console.log(`   ✅ 成功 (状态码: ${response.status})`);
        if (response.body && response.body.success) {
          const dataLength = Array.isArray(response.body.data)
            ? response.body.data.length
            : response.body.data
            ? Object.keys(response.body.data).length
            : 0;
          console.log(`   数据: ${dataLength > 0 ? `${dataLength} 条记录` : '无数据'}`);
          passedTests++;
        } else {
          console.log(`   ⚠️  响应格式异常`);
          console.log(`   响应:`, JSON.stringify(response.body, null, 2));
          failedTests++;
        }
      } else {
        console.log(`   ❌ 失败 (状态码: ${response.status})`);
        console.log(`   响应:`, JSON.stringify(response.body, null, 2));
        failedTests++;
      }
    } catch (error) {
      console.log(`   ❌ 错误: ${error.message}`);
      if (error.code === 'ECONNREFUSED') {
        console.log(`   💡 提示: 后端服务可能未启动，请运行 'npm start' 启动服务`);
      }
      failedTests++;
    }
  }

  console.log('\n' + '='.repeat(60));
  console.log('\n📊 测试结果:');
  console.log(`   ✅ 通过: ${passedTests}`);
  console.log(`   ❌ 失败: ${failedTests}`);
  console.log(`   📈 总计: ${tests.length}\n`);

  if (failedTests === 0) {
    console.log('🎉 所有测试通过！后端接口工作正常。\n');
  } else {
    console.log('⚠️  部分测试失败，请检查后端服务是否正常运行。\n');
  }
}

// 检查后端服务是否可访问
async function checkBackendHealth() {
  try {
    const response = await makeRequest('GET', '/health');
    if (response.status === 200) {
      console.log('✅ 后端服务已启动并可访问\n');
      return true;
    }
  } catch (error) {
    if (error.code === 'ECONNREFUSED') {
      console.log('❌ 无法连接到后端服务\n');
      console.log('💡 请确保：');
      console.log('   1. 后端服务已启动 (在 SMS-backend 目录运行 npm start)');
      console.log('   2. 后端运行在 http://localhost:3000');
      console.log('   3. MongoDB 已启动并连接\n');
      return false;
    }
  }
  return false;
}

// 主函数
async function main() {
  const isHealthy = await checkBackendHealth();
  if (!isHealthy) {
    console.log('⚠️  跳过测试，请先启动后端服务。\n');
    process.exit(1);
  }

  await runTests();
}

main();
